<template>
  <div class="permission-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">权限管理</h1>
        <p class="page-description">管理系统权限和菜单结构</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="handleAdd">
          新增权限
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-form">
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索权限名称或编码..."
          :prefix-icon="Search"
          clearable
          class="search-input"
          @input="handleSearch"
        />
        <el-select
          v-model="searchForm.type"
          placeholder="权限类型"
          clearable
          class="type-select"
          @change="handleSearch"
        >
          <el-option label="菜单" value="1" />
          <el-option label="按钮" value="2" />
          <el-option label="API" value="3" />
        </el-select>
        <el-select
          v-model="searchForm.status"
          placeholder="权限状态"
          clearable
          class="status-select"
          @change="handleSearch"
        >
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
        <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
      </div>
    </div>

    <!-- 权限表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        :loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="permission-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="name" label="权限名称" min-width="200">
          <template #default="{ row }">
            <div class="permission-name">
              <el-icon v-if="row.icon">
                <component :is="getIconComponent(row.icon)" />
              </el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="权限编码" min-width="180" />
        <el-table-column label="权限类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getPermissionTypeTag(row.type)" size="small">
              {{ getPermissionTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" min-width="150" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <TableActionDropdown
              :actions="getPermissionActionList(row)"
              :row="row"
              @action="handlePermissionAction"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 权限详情/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="100px"
        class="permission-form"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input
            v-model="permissionForm.name"
            placeholder="请输入权限名称"
            :disabled="dialogMode === 'view'"
          />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input
            v-model="permissionForm.code"
            placeholder="请输入权限编码"
            :disabled="dialogMode === 'view'"
          />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-radio-group v-model="permissionForm.type" :disabled="dialogMode === 'view'">
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
            <el-radio :label="3">API</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="父级权限" prop="parentId">
          <el-tree-select
            v-model="permissionForm.parentId"
            :data="parentPermissionOptions"
            :props="{ label: 'name', value: 'id' }"
            placeholder="请选择父级权限"
            clearable
            :disabled="dialogMode === 'view'"
            class="full-width"
          />
        </el-form-item>
        <el-form-item label="菜单路径" prop="path" v-if="permissionForm.type === 1">
          <el-input
            v-model="permissionForm.path"
            placeholder="请输入菜单路径"
            :disabled="dialogMode === 'view'"
          />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="permissionForm.type === 1">
          <el-input
            v-model="permissionForm.icon"
            placeholder="请输入图标名称"
            :disabled="dialogMode === 'view'"
          >
            <template #append>
              <el-button @click="showIconSelector">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="permissionForm.sort"
            :min="0"
            :max="9999"
            :disabled="dialogMode === 'view'"
            class="full-width"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="permissionForm.status" :disabled="dialogMode === 'view'">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer v-if="dialogMode !== 'view'">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ dialogMode === 'add' ? '创建' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getIconComponent } from '@/utils/iconMap'
import { permissionAPI } from '@/api/permission'
import {
  Plus, Search, Refresh, View, Edit, Delete
} from '@element-plus/icons-vue'
import TableActionDropdown from '@/components/TableActionDropdown.vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref('add')
const permissionFormRef = ref()
const selectedPermissions = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  type: '',
  status: ''
})

// 权限表单
const permissionForm = reactive({
  id: null,
  name: '',
  code: '',
  type: 1,
  parentId: null,
  path: '',
  icon: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const permissionRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
}

// 表格数据（树形结构）
const tableData = ref([])

// 父级权限选项
const parentPermissionOptions = ref([])

// 计算属性
const dialogTitle = computed(() => {
  const titles = {
    add: '新增权限',
    edit: '编辑权限',
    view: '查看权限'
  }
  return titles[dialogMode.value]
})

// 获取权限类型标签
const getPermissionTypeTag = (type) => {
  const types = {
    1: 'primary',  // 菜单
    2: 'success',  // 按钮
    3: 'warning'   // API
  }
  return types[type] || 'info'
}

// 获取权限类型文本
const getPermissionTypeText = (type) => {
  const types = {
    1: '菜单',
    2: '按钮',
    3: 'API'
  }
  return types[type] || '未知'
}

// 搜索处理
const handleSearch = () => {
  loadTableData()
}

// 刷新数据
const handleRefresh = () => {
  searchForm.keyword = ''
  searchForm.type = ''
  searchForm.status = ''
  loadTableData()
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const response = await permissionAPI.getAllPermissionTree()
    if (response.success) {
      tableData.value = response.data || []
      // 同时更新父级权限选项
      parentPermissionOptions.value = [
        {
          id: null,
          name: '顶级权限',
          children: response.data || []
        }
      ]
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response.message || '加载数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedPermissions.value = selection
}

// 新增权限
const handleAdd = () => {
  dialogMode.value = 'add'
  resetPermissionForm()
  dialogVisible.value = true
}

// 查看权限
const handleView = (row) => {
  dialogMode.value = 'view'
  fillPermissionForm(row)
  dialogVisible.value = true
}

// 编辑权限
const handleEdit = (row) => {
  dialogMode.value = 'edit'
  fillPermissionForm(row)
  dialogVisible.value = true
}

// 删除权限
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await permissionAPI.deletePermission(row.id)
    if (response.success) {
      ElMessage.success('删除成功')
      loadTableData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 显示图标选择器
const showIconSelector = () => {
  ElMessage.info('图标选择器功能待开发')
}

// 提交表单
const handleSubmit = async () => {
  if (!permissionFormRef.value) return
  
  try {
    await permissionFormRef.value.validate()
    submitLoading.value = true
    
    let response
    if (dialogMode.value === 'add') {
      response = await permissionAPI.createPermission(permissionForm)
      if (response.success) {
        ElMessage.success('权限创建成功')
      } else {
        ElMessage.error(response.message || '权限创建失败')
        return
      }
    } else {
      response = await permissionAPI.updatePermission(permissionForm)
      if (response.success) {
        ElMessage.success('权限更新成功')
      } else {
        ElMessage.error(response.message || '权限更新失败')
        return
      }
    }
    
    dialogVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置权限表单
const resetPermissionForm = () => {
  Object.assign(permissionForm, {
    id: null,
    name: '',
    code: '',
    type: 1,
    parentId: null,
    path: '',
    icon: '',
    sort: 0,
    status: 1
  })
  
  if (permissionFormRef.value) {
    permissionFormRef.value.clearValidate()
  }
}

// 填充权限表单
const fillPermissionForm = (row) => {
  Object.assign(permissionForm, {
    id: row.id,
    name: row.name,
    code: row.code,
    type: row.type,
    parentId: row.parentId,
    path: row.path || '',
    icon: row.icon || '',
    sort: row.sort,
    status: row.status
  })
}

// 获取权限操作列表
const getPermissionActionList = (row) => {
  return [
    {
      command: 'view',
      label: '查看',
      icon: View,
      type: 'info'
    },
    {
      command: 'edit',
      label: '编辑',
      icon: Edit,
      type: 'primary'
    },
    {
      command: 'delete',
      label: '删除',
      icon: Delete,
      type: 'danger',
      divided: true
    }
  ]
}

// 处理权限操作事件
const handlePermissionAction = ({ command, row }) => {
  switch (command) {
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleEdit(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      console.warn('未知操作:', command)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
/* 复用之前的样式 */
.permission-management {
  padding: 0;
  background: transparent;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.header-content h1.page-title {
  font-size: 24px;
  font-weight: 700;
  color: hsl(222.2 84% 4.9%);
  margin: 0 0 4px 0;
  line-height: 1.2;
}

.header-content p.page-description {
  color: hsl(215.4 16.3% 46.9%);
  font-size: 14px;
  margin: 0;
}

.header-actions .el-button {
  background: hsl(221.2 83.2% 53.3%);
  border: 1px solid hsl(221.2 83.2% 53.3%);
  color: hsl(210 40% 98%);
  font-weight: 500;
  border-radius: 6px;
}

.search-section {
  background: hsl(0 0% 100%);
  border: 1px solid hsl(214.3 31.8% 91.4%);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.type-select,
.status-select {
  width: 120px;
}

.table-section {
  background: hsl(0 0% 100%);
  border: 1px solid hsl(214.3 31.8% 91.4%);
  border-radius: 8px;
  overflow: hidden;
}

.permission-table {
  width: 100%;
}

.permission-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.permission-form .el-form-item {
  margin-bottom: 20px;
}

.full-width {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .type-select,
  .status-select {
    width: 100%;
  }
}
</style>